package com.link.play.fit.ai.ui.setting

import android.app.Activity
import android.os.Bundle
import androidx.lifecycle.lifecycleScope
import com.google.firebase.firestore.ListenerRegistration
import com.link.play.fit.ai.GlobalConfig
import com.link.play.fit.ai.R
import com.link.play.fit.ai.base.BaseActivity
import com.link.play.fit.ai.base.goToAc
import com.link.play.fit.ai.base.goToAcForResult
import com.link.play.fit.ai.base.viewBind
import com.link.play.fit.ai.bean.LogWeightBean
import com.link.play.fit.ai.bean.UserGuide
import com.link.play.fit.ai.databinding.AcPersonalDetailBinding
import com.link.play.fit.ai.store.CloudStore
import com.link.play.fit.ai.store.CloudStore.DOC_LOG_WEIGHT
import com.link.play.fit.ai.store.CloudStore.DOC_USER_GUIDE
import com.link.play.fit.ai.ui.dialog.CongratulationDialog
import com.link.play.fit.ai.ui.main.MainAc
import com.link.play.fit.ai.utils.DateEx.calculateAge
import com.link.play.fit.ai.utils.DateEx.getTimestampFromDateTime
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class PersonalDetailAc : BaseActivity<AcPersonalDetailBinding>(AcPersonalDetailBinding::inflate) {

    private val observerList = ArrayList<ListenerRegistration>(2)

    private var userData: UserGuide? = null
    private var currentWeight: String = ""
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        lifecycleScope.launch {
            val data = CloudStore.get<UserGuide>(DOC_USER_GUIDE)
            data ?: return@launch
            initView()
            GlobalConfig.imperialMetricFlow.collectLatest {
                if (userData != null) {
                    initData(userData!!)
                }
            }
        }
        binding.flBack.setOnClickListener {
            finish()
        }
        observerList.add(
            CloudStore.observe(
                DOC_USER_GUIDE
            ) { value, error ->
                lifecycleScope.launch(Dispatchers.Main) {
                    userData =
                        if (value?.exists() == true) value.toObject(UserGuide::class.java) else null
                    if (userData != null) initData(userData!!)
                }
            })
        observerList.add(
            CloudStore.observeList(
                DOC_LOG_WEIGHT, DOC_LOG_WEIGHT
            ) { value, error ->
                if (error != null) {
                    return@observeList
                }
                lifecycleScope.launch(Dispatchers.Default) {
                    val data =
                        if (value != null && !value.isEmpty) value.toObjects(LogWeightBean::class.java)
                            .last() else null
                    val currentWeight: String = if (GlobalConfig.imperialMetric) {
                        "${data?.weightKg} kg"
                    } else {
                        "${data?.weightLbs} lbs"
                    }
                    withContext(Dispatchers.Main) {
                        viewBind {
                            tvWeight.text = currentWeight
                        }
                    }
                }
            })
    }

    fun initView() {
        binding.flGoalWeight.setOnClickListener {
            goToAc(SetUserInfoAc::class.java) {
                putExtra(SetUserInfoAc.Type, SetUserInfoAc.goalWeight)
            }
        }
        binding.llWeight.setOnClickListener {
//            goToAc(SetUserInfoAc::class.java) {
//                putExtra(SetUserInfoAc.Type, SetUserInfoAc.weight)
//            }
            lifecycleScope.launch {
                val before = CloudStore.get<UserGuide>(DOC_USER_GUIDE) ?: UserGuide()
                val result = (this@PersonalDetailAc).goToAcForResult(SetWeightAc::class.java)
                val after = CloudStore.get<UserGuide>(DOC_USER_GUIDE) ?: UserGuide()
                if (result.resultCode == Activity.RESULT_OK) {

                    if (after.imperialMetric) {
                        val change = after.weightKg - before.weightKg
                        if (before.goal == 0 && change <= 0) {
                            return@launch
                        }
                        if (before.goal == 2 && change >= 0) {
                            return@launch
                        }
                        CongratulationDialog(this@PersonalDetailAc).showDialog(true, change, after.weightKg)
                    } else {
                        val change = after.weightLbs - before.weightLbs
                        if (before.goal == 0 && change <= 0) {
                            return@launch
                        }
                        if (before.goal == 2 && change >= 0) {
                            return@launch
                        }
                        CongratulationDialog(this@PersonalDetailAc).showDialog(false, change, after.weightLbs)
                    }

                }

            }
        }
        binding.llHeight.setOnClickListener {
            goToAc(SetUserInfoAc::class.java) {
                putExtra(SetUserInfoAc.Type, SetUserInfoAc.height)
            }
        }
        binding.llBirth.setOnClickListener {
            goToAc(SetUserInfoAc::class.java) {
                putExtra(SetUserInfoAc.Type, SetUserInfoAc.age)
            }
        }
        binding.llGender.setOnClickListener {
            goToAc(SetUserInfoAc::class.java) {
                putExtra(SetUserInfoAc.Type, SetUserInfoAc.gender)
            }
        }
    }

    fun initData(data: UserGuide) {
        val age = calculateAge(
            getTimestampFromDateTime(
                data.bornYear, data.bornMonth,
                data.bornDay, 1, 1
            )
        ).toString()
        val height =
            if (GlobalConfig.imperialMetric) "${data.heightCm} cm" else "${data.heightFt} ft ${data.heightIn} in"
        val weight =
            if (GlobalConfig.imperialMetric) "${data.weightKg} kg" else "${data.weightLbs} lb"
        val birth = "${data.bornMonth}/${data.bornDay}/${data.bornYear}"
        val goalWeight =
            if (GlobalConfig.imperialMetric) "${data.goalWeightKg} kg" else "${data.goalWeightLbs} lb"
        binding.tvGoalWeight.text = goalWeight
        binding.tvBirth.text = birth
//        binding.tvWeight.text = weight
        binding.tvHeight.text = height
        binding.tvGender.text = when (data.gender) {
            //0 male ; 1 female ; 2 other
            0 -> {
                resources.getString(R.string.male)
            }

            1 -> {
                resources.getString(R.string.female)
            }

            else -> {
                resources.getString(R.string.other)
            }
        }.toString()
    }

    override fun onDestroy() {
        super.onDestroy()
        observerList.forEach {
            it.remove()
        }
        observerList.clear()
    }
}